from celery import Celery
from django.core.mail import send_mail
from django.conf import settings
from django.template import loader, RequestContext
import time

#任务处理者 Django环境初始化
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dailyfresh.settings')
django.setup()

app = Celery('celery_task.tasks',broker='redis://127.0.0.1:6379/8')

@app.task
def send_register_active_email(to_email, username, token):
    '''注册激活邮件函数'''
    subject = '天天生鲜激活信息'
    message = ''
    sender = settings.EMAIL_FROM
    reveiver = [to_email]
    html_mesage = "<h1>%s,欢迎成为天天生鲜注册会员</h1><p>请点击以下链接激活账户</p><a href='http://127.0.0.1:8001/user/active/%s'>激活账户</a>" % (
    username, token)
    send_mail(subject, message, sender, reveiver, html_message=html_mesage)
    # print('send email success')
    time.sleep(10)


@app.task
def generate_static_html():
    '''生成首页静态页面'''
    # 动态获取首页内容

    context = {

    }
    # 使用模板
    # 加载模板文件
    temp = loader.get_template('static_index.html')
    # 定义模板上下文
    # context = RequestContext(request, con_text)
    # 渲染模板
    static_index_html = temp.render(context)

    file_path = os.path.join(settings.BASE_DIR, 'static/index.html')
    with open(file_path, 'w') as f:
        f.write(static_index_html)
